package com.leo.train.business.controller.web;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.leo.train.business.dto.ConfirmOrderSaveDto;
import com.leo.train.business.service.BeforeConfirmOrderService;
import com.leo.train.business.service.ConfirmOrderService;
import com.leo.train.common.exception.BusinessExceptionEnum;
import com.leo.train.common.resp.CommonResp;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/confirmOrder")
@Slf4j
public class ConfirmOrderController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private BeforeConfirmOrderService beforeConfirmOrderService;
    @Autowired
    private ConfirmOrderService confirmOrderService;
//    @Value("${spring.profiles.active}")
//    private String env; // 获取环境变量

    /**
     * 确认订单列表
     * @param confirmOrderSaveDto
     * @return
     */
    // 接口的资源名称不要和接口路径一致，会导致限流后走不到降级方法中
    @SentinelResource(value = "confirmOrderDo", blockHandler = "doConfirmBlock")
    @PostMapping("/do")
    public CommonResp<Object> doConfirm(@RequestBody @Valid ConfirmOrderSaveDto confirmOrderSaveDto) {
//        if(!env.equals("dev")) {
            // 图形验证码校验
            String imageCode = confirmOrderSaveDto.getImageCode();
            String imageCodeToken = confirmOrderSaveDto.getImageCodeToken();
            String imageCodeInRedis = redisTemplate.opsForValue().get(imageCodeToken);
            if(imageCodeInRedis == null) {
                return new CommonResp<>(false, "图片验证码已过期",null);
            }
            if(!imageCodeInRedis.equalsIgnoreCase(imageCode)) {
                return new CommonResp<>(false, "图片验证码不正确", null);
            } else {
                // 从redis中删除验证码
                redisTemplate.delete(imageCodeToken);
            }
//        }
        // 预处理订单
        Long id = beforeConfirmOrderService.beforeDoConfirm(confirmOrderSaveDto);
        return new CommonResp<>(String.valueOf(id));
    }

    /** 降级方法，需包含限流方法的所有参数和BlockException参数，且返回值要保持一致
     * @param confirmOrderSaveDto
     * @param e
     */
    public CommonResp<Object> doConfirmBlock(ConfirmOrderSaveDto confirmOrderSaveDto, BlockException e) {
        log.info("ConfirmOrderController购票请求被限流：{}", confirmOrderSaveDto);
        CommonResp<Object> commonResp = new CommonResp<>();
        commonResp.setSuccess(false);
        commonResp.setMessage(BusinessExceptionEnum.CONFIRM_ORDER_FLOW_EXCEPTION.getDesc());
        return commonResp;

    }


    @GetMapping("/query-line-count/{id}")
    public CommonResp<Integer> queryLineCount(@PathVariable Long id) {
        Integer count = confirmOrderService.queryLineCount(id);
        return new CommonResp<>(count);
    }

    @GetMapping("/cancel/{id}")
    public CommonResp<Integer> cancel(@PathVariable Long id) {
        Integer count = confirmOrderService.cancel(id);
        return new CommonResp<>(count);
    }
}
